package org.freespace.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.freespace.model.JmxPlugin;
import org.freespace.model.JmxScriptPlugin;
import org.freespace.model.Machine;
import org.freespace.service.IJmxPluginService;
import org.freespace.service.IJmxScriptPluginService;
import org.freespace.utils.SessionUtil;
import org.freespace.utils.response.CommonResult;
import org.freespace.vo.JmxPluginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * jmx插件表 前端控制器
 * </p>
 *
 * @author liuqi
 * @since 2023-04-28
 */
@Slf4j
@RestController
@RequestMapping("/jmx-plugin")
public class JmxPluginController {

    String fileStoreDir = "/var/www/html/plugin";

    @Autowired
    IJmxPluginService jmxPluginService;

    @Autowired
    IJmxScriptPluginService scriptPluginService;

    @PostMapping(value = "list")
    public CommonResult list(@RequestBody JmxPluginVO vo) {
        Page<JmxPlugin> page = new Page<>(vo.getCurrentPage(), vo.getPageSize());
        Wrapper<JmxPlugin> wrapper = Wrappers.query();
        if(StringUtils.isNotBlank(vo.getCondition())) {
            wrapper = Wrappers.<JmxPlugin>lambdaQuery()
                    .like(JmxPlugin::getId, vo.getCondition())
                    .or().like(JmxPlugin::getPluginName, vo.getCondition())
                    .or().like(JmxPlugin::getCreateBy, vo.getCondition());
        }
        IPage<JmxPlugin> data = jmxPluginService.page(page, wrapper);
        return CommonResult.success(data);
    }

    @PostMapping("bindPlugins")
    public CommonResult bindPlugins(@RequestBody JmxPluginVO vo) {
        return CommonResult.success(jmxPluginService.bindPageList(vo));
    }

    @PostMapping("unBindPlugins")
    public CommonResult unBindPlugins(@RequestBody JmxPluginVO vo) {
        return CommonResult.success(jmxPluginService.unBindPageList(vo));
    }


    @PostMapping("bindOrUnbind")
    public CommonResult bindOrUnbind(@RequestBody JmxPluginVO vo) {
        if (vo.getType() == 0) {
            LambdaQueryWrapper<JmxScriptPlugin> w = Wrappers.<JmxScriptPlugin>lambdaQuery().eq(JmxScriptPlugin::getScriptId, vo.getScriptId())
                    .eq(JmxScriptPlugin::getPluginId, vo.getPluginId());
            scriptPluginService.remove(w);
        } else {
            JmxScriptPlugin scriptPlugin = new JmxScriptPlugin();
            scriptPlugin.setScriptId(vo.getScriptId());
            scriptPlugin.setPluginId(vo.getPluginId());
            scriptPlugin.setCreateBy(SessionUtil.getCurrentUser());
            scriptPlugin.setCreateTime(LocalDateTime.now());
            scriptPluginService.save(scriptPlugin);
        }
        return CommonResult.success();
    }


    @PostMapping("save")
    public CommonResult save(@RequestPart("file") MultipartFile file, @RequestPart("pluginInfo") JmxPlugin plugin) throws IOException {
        if (file == null || file.getInputStream() == null) {
//            throw
        }

        plugin.setCreateBy(SessionUtil.getCurrentUser());
        plugin.setLastUpdateBy(SessionUtil.getCurrentUser());
        plugin.setCreateTime(LocalDateTime.now());
        plugin.setLastUpdateTime(LocalDateTime.now());

        jmxPluginService.saveOrUpdate(plugin);

        String fullFileName = fileStoreDir + "/" + plugin.getId() + "/" + file.getOriginalFilename();
        plugin.setPath(fullFileName);
        jmxPluginService.updateById(plugin);

        File newFile = FileUtil.touch(new File(fullFileName));
        FileUtil.writeFromStream(file.getInputStream(), newFile, true);

        return CommonResult.success();
    }

    @GetMapping("delete/{id}")
    public CommonResult save(@PathVariable("id") int id) {
        jmxPluginService.removeById(id);
        FileUtil.del(new File(fileStoreDir + "/" + id));
        return CommonResult.success();
    }
}
